﻿@inject IUserService userService

@if( !string.IsNullOrEmpty(FieldValue) || (Editable && allowedToEdit) )
{
    <div class="imagefield">
        <label class="imagefield-label" title="@Tooltip">
            @FieldName:
            @if ( string.IsNullOrEmpty(Href) )
            {
                @if ( editing )
                {
                    <input @ref="inputField" class="imagefield-edit" placeholder="@FieldValue" value="@FieldValue" @onchange="ValueChanged" @onblur="LostFocus"/>
                }
                else
                {
                    @if ( Editable && allowedToEdit )
                    {
                        <span class="imagefield-val" @onclick="EditField">@FieldValue</span>
                        <i class="fas fa-edit" title="@EditTooltip" @onclick="EditField"/>
                    }
                    else
                    {
                        <span class="imagefield-val">@FieldValue</span>
                    }
                }
            }
            else
            {
                <NavLink href="@Href">@FieldValue</NavLink>
            }

            @ChildContent

        </label>
    </div>
}

@code {

    [Parameter] public string FieldName { get; set; }

    [Parameter] public string Title { get; set; }

    [Parameter] public bool Editable { get; set; }

    [Parameter] public string Href { get; set; }

    [Parameter] public string FieldValue { get; set; }

    [Parameter] public EventCallback<ChangeEventArgs> OnValueChanged { get; set; }

    [Parameter] public RenderFragment ChildContent { get; set; }

    private bool allowedToEdit = false;
    private bool editing = false;
    private ElementReference inputField;
    private string Tooltip => Title?.Trim();
    private string EditTooltip => $"Click here to edit the {FieldName.ToLower()}";

    private async void ValueChanged(ChangeEventArgs args)
    {
        editing = false;
        StateHasChanged();

        await OnValueChanged.InvokeAsync(args);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if( !firstRender )
        {
            if( editing )
            {
                await inputField.FocusAsync();
            }
        }
    }

    protected override async Task OnInitializedAsync()
    {
        if( string.IsNullOrEmpty(Title) )
            Title = FieldValue;

        allowedToEdit = await userService.PolicyApplies(PolicyDefinitions.s_IsEditor);

        base.OnInitialized();
    }

    private void LostFocus()
    {
        editing = false;
        StateHasChanged();
    }

    private void EditField()
    {
        editing = true;
        StateHasChanged();
    }

}